package com.k.kppcloud.gateway.fiter;

import com.k.kppcloud.gateway.util.GatewayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义Ip黑名单过滤器
 * @author pnoker
 */
@Slf4j
public class BlackIpGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String remoteIp = GatewayUtil.getRemoteIp(request);
        String path = request.getPath().toString();
        log.info("BlackIpGlobalFilter -> Request: ip: {}; path: {}; code: {}", remoteIp, path, exchange.getResponse().getStatusCode());
        if (isBlackList(remoteIp)) {
            log.error("BlackIpGlobalFilter -> Forbidden Ip: {}", remoteIp);
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    private boolean isBlackList(String ip){
        boolean isBlack = false;
        if("10.110.12.33".equals(ip)){
            isBlack = true;
        }
        return isBlack;
    }
}
